# 根据模板页眉，整体替换目标页眉，并将部分内容替换为原页眉内容，
# 模板文件要放在文件夹下
from docx import Document
from docx.oxml.ns import qn
import os
import win32com
from win32com.client import Dispatch, constants


# 获取全部文件的路径
def get_filelist(dir):
    filelist = []
    for home, dirs, files in os.walk(dir):
        for filename in files:
            # 文件列表。包含完整路径
            filelist.append(os.path.join(home, filename))
            # 文件名列表，只包含文件名
            # filelist.append(filename)
    return filelist


path = input('输入文件夹路径：')
filelist = get_filelist(path)

template = '模板.docx'
w = win32com.client.Dispatch('Word.Application')
w.Visible = True
w.DisplayAlerts = False


doc = w.Documents.Open(path + '//' + template)
# w.ActiveDocument.Sections[0].Footers[0].Range.Copy() # 复制页脚
w.ActiveDocument.Sections[0].Headers[0].Range.Copy() # 复制页眉
doc.Close()


for file in filelist:
    if file.endswith('.doc') or file.endswith('.docx'):
        doc1 = Document(file)
        value = {}
        j = 0
        for section in doc1.sections:
            try:
                header = section.header
                tables = header.tables
                title = tables[0].rows[2].cells[0].text  # 获取原页眉表格中的标题
                numb = tables[0].rows[0].cells[1].text  # 获取原页眉表格中的文件编号
                value[title] = numb
            except:
                value['empty'] = 'empty'
        print('原页眉内容：',value)
        try:
            doc2 = w.Documents.Open(file)
            # 如果首页没有页眉则跳过不粘帖
            if 'empty' in value:
                for i in range(1,len(doc1.sections)):
                    w.ActiveDocument.Sections[i].Headers[0].Range.Paste()
            else:
                for i in range(len(doc1.sections)):
                    w.ActiveDocument.Sections[i].Headers[0].Range.Paste()
            w.ActiveDocument.SaveAs(file)
            doc2.Close()
        except:
            pass

        doc3 = Document(file)
        for title, numb in value.items():
            try:
                doc3.sections[j].header.tables[0].rows[1].cells[0].text = numb
                for paragraph in doc3.sections[j].header.tables[0].rows[1].cells[0].paragraphs:
                    for run in paragraph.runs:
                        run.font.name = u'仿宋'
                        run._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋')
                doc3.sections[j].header.tables[0].rows[2].cells[0].text = title
                for paragraph in doc3.sections[j].header.tables[0].rows[2].cells[0].paragraphs:
                    for run in paragraph.runs:
                        run.font.name = u'仿宋'
                        run._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋')
                j += 1
            except:
                pass
        doc3.save(file)
    print(file,'>>>替换完成！！')

w.Quit()



